//vou usar em todos os programas;)

#include "inicializacao.h"

#include <termios.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <stdio.h>

int kbhit()
{
    struct termios oldt, newt;
    int ch;
    int oldf;

    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

    ch = getchar();

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    fcntl(STDIN_FILENO, F_SETFL, oldf);

    if(ch != EOF)
    {
        ungetc(ch, stdin);
        return 1;
    }
    return 0;
}

void LimpaBuffer()
{
    struct termios oldt, newt;
    int ch;
    int oldf;
retiramaisum:
    tcgetattr(STDIN_FILENO, &oldt);
    newt = oldt;
    newt.c_lflag &= ~(ICANON | ECHO);
    tcsetattr(STDIN_FILENO, TCSANOW, &newt);
    oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
    fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

    ch = getchar();

    tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
    fcntl(STDIN_FILENO, F_SETFL, oldf);

    if(ch != EOF)
    {
        //ungetc(ch, stdin);
        goto retiramaisum;
    }
    return;
}

int Meugetch()
{
    struct termios oldt,
            newt;
    int            ch;
    tcgetattr( STDIN_FILENO, &oldt );
    newt = oldt;
    newt.c_lflag &= ~( ICANON | ECHO );
    tcsetattr( STDIN_FILENO, TCSANOW, &newt );
    ch = getchar();
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
    return ch;
}

void gotoXY(int x, int y)
{
    //sequência para posicionar linha e coluna
    //só funciona no Linux
    cout << "\033[" << y << ";" << x << "f";
    cout.flush();
    return;
}

void LimparTela()
{
    cout << "\033[40;032m" << "\033[2J\033[0;0f"; //Corrigido, acho
    return;
}


void escreveCutscene(string frase)
{
    for (int i =0; i <frase.size(); i++)
    {
        cout << frase[i];
        if (kbhit())
            return;
        usleep(50080);
    }
    gotoXY(28,23);
    cout << "\033[40;5;37mPress Enter to Continue";
    Meugetch();
    LimparTela();
    return;
}

XY retornaTamanhoTela() // precisa de uma classe XY que tenha int x, y;
{

    struct winsize ws;
    int fd=open("/dev/tty",O_RDWR);

    ioctl(fd,TIOCGWINSZ,&ws);

    printf("rows %i\n",ws.ws_row);
    printf("cols %i\n",ws.ws_col);
    XY a( ws.ws_col, ws.ws_col, 0,0);
    return a;
}
